const express = require('express');
const puppeteer = require('puppeteer');

const app = express();
const port = 3000;

let browser; // 全局变量，用于复用浏览器实例

// 服务启动时创建浏览器实例
(async () => {
  browser = await puppeteer.launch();
  console.log('Service started, browser instance created.');
})();

// 处理截图请求
app.get('/screenshot', async (req, res) => {
    const startTime = Date.now(); // Record the start time
  const url = req.query.url;
  const elementSelector = req.query.elementSelector;
  const width = Number(req.query.width) || 1920;
  let height = Number(req.query.height) || 2048;

  if (!url || !elementSelector) {
    return res.status(400).send('Missing required query parameters: url or elementSelector.');
  }
  console.log('url is ',url);
  console.log('selector is ',elementSelector);
  try {
    const page = await browser.newPage();
    // await page.setBypassCSP(true);
    await page.setViewport({
        width: width, // 设置视窗宽度
        height: height, // 设置视窗高度
        deviceScaleFactor: 2 // 设置设备像素比，增加这个值可以提高截图的分辨率
      });
    
    await page.goto(url, { waitUntil: 'networkidle2' });
    await page.evaluate(() => {
        // 这里设置sessionStorage的键值对
        // 假设登录人的信息存储在sessionStorage的'user'键下
            localStorage.setItem('token', 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJqaWFuZ196aHVvIiwiZXhwIjoxNzI3MDMxODYyLCJ1c2VyTmFtZSI6IjAwMTc3MeWnnOWNkyJ9.FDBTDsoVsVZBAY5w7q6CUCaahUNICpkmtF-LmsSjFjqB8BxyMIfKwZMVnwilB8drrlKGs6ikP9mU5nwVxdhuFw');
            localStorage.setItem('username', '001771姜卓');
        });
    await page.goto(url, { waitUntil: 'networkidle2' });        
    await page.waitForSelector(elementSelector);
    const element = await page.$(elementSelector);
    const buffer = await element.screenshot({ type: 'png' });
    console.log('Buffer size:', buffer.length);
    // 手动设置Content-Type
    res.setHeader('Content-Type', 'image/png');
    res.write(buffer);
    res.end();
    await page.close();
    const endTime = Date.now(); // Record the end time
    const elapsedTime = (endTime - startTime) / 1000; // Calculate the elapsed time in seconds
    console.log(`Transaction completed in ${elapsedTime.toFixed(2)} seconds`);
  } catch (error) {
    console.error('Error taking screenshot:', error);
    res.status(500).send('Internal Server Error');
  }
});

// 服务关闭时关闭浏览器实例
process.on('SIGINT', async () => {
  await browser.close();
  console.log('Service stopped, browser instance closed.');
  process.exit(0);
});

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});